package com.alexgaoyh.andriodtest;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alexgaoyh.andriodtest.adapter.GalleryIndexAdapter;
import com.alexgaoyh.andriodtest.adapter.ListViewFrame_1_1_Adapter;
import com.alexgaoyh.andriodtest.bean.Frame_1_1;
import com.alexgaoyh.andriodtest.bean.Frame_1_1_List;
import com.alexgaoyh.andriodtest.bean.Notice;
import com.alexgaoyh.andriodtest.common.util.StringUtils;
import com.alexgaoyh.andriodtest.common.util.UIHelper;
import com.alexgaoyh.andriodtest.tempClass.PackageData;
import com.alexgaoyh.andriodtest.util.DetailGallery;
import com.alexgaoyh.andriodtest.util.PullToRefreshListView;
import com.alexgaoyh.andriodtest.util.ScrollLayout;
import com.alexgaoyh.andriodtest.util.Tool;


public class MainActivity extends Activity {
	
	private LinearLayout headerLinearlayout;
	
	//页面顶部的按钮
	private RadioButton[] mButtons;
	
	//左右滑动控件
	private ScrollLayout mScrollLayout;
	
	//顶部的RadioButton 个数
	private int headerRadioButtionCount;
	
	//第一屏frame_1包含的两个下拉刷新控件
	private PullToRefreshListView frame_1_listview_1;
	
	//首页第一屏第一个实体信息
	private List<Frame_1_1> frame_1_1_Data = new ArrayList<Frame_1_1>();
	
	
	//首页第一屏第一个按钮对应的下拉刷新适配器UI
	private ListViewFrame_1_1_Adapter frame_1_1_Adapter;
	
	//首页第一屏第一个按钮对应的下部刷新显示 视图
	private View frame_1_1_footer;
	
	//首页第一屏第一个按钮对应的下部刷新显示 文本显示
	private TextView frame_1_1_foot_more;
	
	//首页第一屏第一个按钮对应的下部刷新显示  下拉框效果显示
	private ProgressBar frame_1_1_foot_progress;
	
	//Handle
	private Handler lvFrame_1_1_Handler;
	
	//全局context
	private Context context;
	
	//第二屏幻灯片部分
	private Gallery myGallery;//幻灯片
	private RadioGroup gallery_points;////幻灯片下面的圆点部分
	private RadioButton[] gallery_point;//按钮部分
	private LinearLayout GalleryLayout;//幻灯片对应的layout

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		context = getApplicationContext();
		
		//初始化UI组建
		this.initUIComponent();
		
		this.initHeaderRadioButtonisChecked();
		this.initHeaderScrolllayout();
		this.initFrame1();
		
		this.initDetailGallery();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	/**
	 * 先初始化各个UI组建部分
	 */
	public void initUIComponent() {
		
		//初始化顶部的布局
		headerLinearlayout = (LinearLayout) findViewById(R.id.main_linearlayout_header);
		
		//初始化顶部RadioButton 个数
		headerRadioButtionCount = headerLinearlayout.getChildCount();
		
		//初始化RadioButtion
		mButtons = new RadioButton[headerRadioButtionCount/2];
		
	}
	
	/**
	 * 初始化顶部多个RadioButton的点击选中与否的状态操作
	 */
	public void initHeaderRadioButtonisChecked() {
		
		//初始化顶部RadioButtion
		for (int i = 0; i < headerRadioButtionCount/2; i++) {
			mButtons[i] = (RadioButton) headerLinearlayout.getChildAt(i * 2);
			mButtons[i].setTag(i);
			mButtons[i].setChecked(false);
		}
		
		//初始化RadioButton之后，增加点击监听事件
		for (int i = 0; i < mButtons.length; i++) {
			mButtons[i].setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					
					int pos = (Integer) (v.getTag());
					
					//移除所有RadioButtion部分的选中状态
					removeAllHeaderRadioButtonChecked();
					//设置当前点击的RadioButton为选中状态
					mButtons[pos].setChecked(true);
					
					mScrollLayout.snapToScreen(pos);
				}
			});
		}
		
		//初始化时，第一个RadioButton设置为选中状态
		mButtons[0].setChecked(true);
	}
	
	/**
	 * 初始化左右滑动控件部分，并对滑动操作增加监听事件，滑动操作带动顶部RadioButton部分的选中状态调整
	 */
	public void initHeaderScrolllayout() {
		mScrollLayout = (ScrollLayout) findViewById(R.id.main_scrolllayout);
		
		mScrollLayout.SetOnViewChangeListener(new ScrollLayout.OnViewChangeListener() {
			public void OnViewChange(int viewIndex) {
				setCurPoint(viewIndex, mScrollLayout.getChildCount());
			}
		});
	}
	
	/**
	 * 初始化第一屏frame_1 所对应的操作
	 */
	public void initFrame1() {
		
		initFrame1ListView();
		
		initFrameListViewData();
	}
	
	/**
	 * 初始化第一屏的列表信息
	 */
	public void initFrame1ListView() {
		frame_1_1_Adapter = new ListViewFrame_1_1_Adapter(this, frame_1_1_Data,R.layout.frame_1_listview_1_item);
		
		frame_1_1_footer = getLayoutInflater().inflate(R.layout.listview_footer,null);
		frame_1_1_foot_more = (TextView) frame_1_1_footer.findViewById(R.id.listview_foot_more);
		frame_1_1_foot_progress = (ProgressBar) frame_1_1_footer.findViewById(R.id.listview_foot_progress);
		
		frame_1_listview_1 = (PullToRefreshListView) findViewById(R.id.frame_1_listview_1);
		frame_1_listview_1.addFooterView(frame_1_1_footer);// 添加底部视图 必须在setAdapter前
		frame_1_listview_1.setAdapter(frame_1_1_Adapter);
		
		
		frame_1_listview_1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击头部、底部栏无效
				if (position == 0 || view == frame_1_1_footer)
					return;

				Frame_1_1 news = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					news = (Frame_1_1) view.getTag();
				} else {
					TextView tv = (TextView) view
							.findViewById(R.id.frame_1_listitem_1_item_title);
					news = (Frame_1_1) tv.getTag();
				}
				if (news == null)
					return;

			}
		});
		frame_1_listview_1.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				frame_1_listview_1.onScrollStateChanged(view, scrollState);

				// 数据为空--不用继续下面代码了
				if (frame_1_1_Data.isEmpty()) {
					return;
				}

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(frame_1_1_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(frame_1_listview_1.getTag());
				
				if (scrollEnd && lvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					frame_1_listview_1.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					frame_1_1_foot_more.setText(R.string.load_ing);
					frame_1_1_foot_progress.setVisibility(View.VISIBLE);
					loadFrame_1_1_Data(lvFrame_1_1_Handler,UIHelper.LISTVIEW_ACTION_SCROLL);
					
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				frame_1_listview_1.onScroll(view, firstVisibleItem, visibleItemCount,totalItemCount);
			}
		});
		frame_1_listview_1.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			public void onRefresh() {
				loadFrame_1_1_Data(lvFrame_1_1_Handler,UIHelper.LISTVIEW_ACTION_REFRESH);
			}
		});
		
	}
	
	/**
	 * 初始化所有ListView数据
	 */
	private void initFrameListViewData() {
		// 初始化Handler
		lvFrame_1_1_Handler = this.getLvHandler(frame_1_listview_1, frame_1_1_Adapter,frame_1_1_foot_more, frame_1_1_foot_progress, 20);
				
		// 加载数据
		if (frame_1_1_Data.isEmpty()) {
			loadFrame_1_1_Data(lvFrame_1_1_Handler,UIHelper.LISTVIEW_ACTION_INIT);
		}
	}
	
	/**
	 * 移除顶部RadioButtion按钮的选中事件
	 */
	private void removeAllHeaderRadioButtonChecked() {
		for (int i = 0; i < mButtons.length; i++) {
			mButtons[i].setChecked(false);
		}
	}
	
	/**
	 * 设置顶部栏当前焦点
	 * 
	 * @param index
	 */
	private void setCurPoint(int index, int allCount) {
		if (index < 0 || index > allCount - 1){
			return;
		}
		removeAllHeaderRadioButtonChecked();
		mButtons[index].setChecked(true);
	}
	
	/**
	 * frame_1 第一屏下对应的多个按钮的点击选中效果操作
	 * @param btn
	 * @return
	 */
	private View.OnClickListener frame1BtnClick(final Button btn) {
		return new View.OnClickListener() {
			public void onClick(View v) {
				
			}
		};
	}
	
	/**
	 * 获取listview的初始化Handler
	 * 
	 * @param lv
	 * @param adapter
	 * @return
	 */
	private Handler getLvHandler(final PullToRefreshListView lv, final BaseAdapter adapter, final TextView more, final ProgressBar progress, final int pageSize) {
		return new Handler() {
			public void handleMessage(Message msg) {
				//
				if (msg.what >= 0) {
					// listview数据处理
					Notice notice = handleLvData(msg.what, msg.obj, msg.arg2,msg.arg1);
					
					//底部显示是否还有数据  （已加载全部 ||更多 ）
					if (msg.what < pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_FULL);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_full);
					} else if (msg.what == pageSize) {
						lv.setTag(UIHelper.LISTVIEW_DATA_MORE);
						adapter.notifyDataSetChanged();
						more.setText(R.string.load_more);

					}
				}
				
				if (adapter.getCount() == 0) {
					lv.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					more.setText(R.string.load_empty);
				}
				progress.setVisibility(ProgressBar.GONE);
				if (msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH) {
					lv.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
					lv.setSelection(0);
				} else if (msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG) {
					lv.onRefreshComplete();
					lv.setSelection(0);
				}
			}
		};
	}
	
	/**
	 * 线程加载数据
	 * 
	 * @param handler
	 *            处理器
	 * @param action
	 *            动作标识
	 */
	private void loadFrame_1_1_Data(final Handler handler, final int action) {
		new Thread() {
			public void run() {
				Message msg = new Message();
				
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL){
					isRefresh = true;
				}
				
				Frame_1_1_List list = PackageData.packageFrame_1_1List(isRefresh);
				msg.what = list.getPageSize();
				msg.obj = list;
				msg.arg1 = action;
				msg.arg2 = UIHelper.LISTVIEW_DATATYPE_NEWS;
				handler.sendMessage(msg);
			}
		}.start();
	}
	
	
	/**
	 * listview数据处理
	 * 
	 * @param what
	 *            数量
	 * @param obj
	 *            数据
	 * @param objtype
	 *            数据类型
	 * @param actiontype
	 *            操作类型
	 * @return notice 通知信息
	 */
	private Notice handleLvData(int what, Object obj, int objtype,int actiontype) {
		Notice notice = null;
		switch (actiontype) {
			case UIHelper.LISTVIEW_ACTION_INIT:
				
			case UIHelper.LISTVIEW_ACTION_REFRESH:
			
			case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
				int newdata = 0;// 新加载数据-只有刷新动作才会使用到
				switch (objtype) {
					case UIHelper.LISTVIEW_DATATYPE_NEWS:
						Frame_1_1_List nlist = (Frame_1_1_List) obj;
						if (actiontype == UIHelper.LISTVIEW_ACTION_REFRESH) {
							if (frame_1_1_Data.size() > 0) {
								for (Frame_1_1 news1 : nlist.getNewslist()) {
									boolean b = false;
									for (Frame_1_1 news2 : frame_1_1_Data) {
										if (news1.getId() == news2.getId()) {
											b = true;
											break;
										}
									}
									if (!b){
										newdata++;
									}
								}
							} else {
								newdata = what;
							}
						}
						//frame_1_1_Data.clear();// 先清除原有数据
						if(nlist != null && nlist.getNewslist() != null && !nlist.getNewslist().isEmpty() ) {
							frame_1_1_Data.addAll(0,nlist.getNewslist());
						}
						break;
				}
			
			case UIHelper.LISTVIEW_ACTION_SCROLL:
				switch (objtype) {
					case UIHelper.LISTVIEW_DATATYPE_NEWS:
						Frame_1_1_List list = (Frame_1_1_List) obj;
						notice = list.getNotice();
						if (frame_1_1_Data.size() > 0) {
							for (Frame_1_1 news1 : list.getNewslist()) {
								boolean b = false;
								for (Frame_1_1 news2 : frame_1_1_Data) {
									if (news1.getId() == news2.getId()) {
										b = true;
										break;
									}
								}
								if (!b)
									frame_1_1_Data.add(news1);
							}
						} else {
							frame_1_1_Data.addAll(list.getNewslist());
						}
						break;
				}
				
		}
		return notice;
	}
	
	
	private void initDetailGallery() {
		myGallery = (DetailGallery)findViewById(R.id.myGallery);
		gallery_points = (RadioGroup) this.findViewById(R.id.galleryRaidoGroup);
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(R.drawable.banner1);
		list.add(R.drawable.banner2);
		list.add(R.drawable.banner3);
		GalleryIndexAdapter adapter = new GalleryIndexAdapter(list, context);
		myGallery.setAdapter(adapter);
		//设置小按钮
		gallery_point = new RadioButton[list.size()];
		for (int i = 0; i < gallery_point.length; i++) {
			GalleryLayout = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.gallery_icon, null);
			gallery_point[i] = (RadioButton) GalleryLayout.findViewById(R.id.gallery_radiobutton);
			gallery_point[i].setId(i);/* 设置指示图按钮ID */
			int wh = Tool.dp2px(context, 10);
			RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(wh, wh); // 设置指示图大小
			gallery_point[i].setLayoutParams(layoutParams);
			layoutParams.setMargins(4, 0, 4, 0);// 设置指示图margin值
			gallery_point[i].setClickable(false);/* 设置指示图按钮不能点击 */
			GalleryLayout.removeView(gallery_point[i]);//一个子视图不能指定了多个父视图
			gallery_points.addView(gallery_point[i]);/* 把已经初始化的指示图动态添加到指示图的RadioGroup中 */
		}
		
		myGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				gallery_points.check(gallery_point[arg2%gallery_point.length].getId());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	/** 展示图控制器，实现展示图切换 */
	final Handler handler_gallery = new Handler() {
		public void handleMessage(Message msg) {
			/* 自定义屏幕按下的动作 */
			MotionEvent e1 = MotionEvent.obtain(SystemClock.uptimeMillis(),
					SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
					89.333336f, 265.33334f, 0);
			/* 自定义屏幕放开的动作 */
			MotionEvent e2 = MotionEvent.obtain(SystemClock.uptimeMillis(),
					SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN,
					300.0f, 238.00003f, 0);
			
			myGallery.onFling(e2, e1, -800, 0);
			/* 给gallery添加按下和放开的动作，实现自动滑动 */
			super.handleMessage(msg);
		}
	};
	
	protected void onResume() {
		autogallery();
		super.onResume();
	};
	
	
	private void autogallery() {
		/* 设置定时器，自动切换展示图 */
		Timer time = new Timer();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				Message m = new Message();
				handler_gallery.sendMessage(m);
			}
		};
		time.schedule(task, 8000, 3000);
	}
}
